package com.dxy.hms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxy.hms.base.AppConstant;
import com.dxy.hms.base.Resp;
import com.dxy.hms.base.StatusMessageEnum;
import com.dxy.hms.base.UnifiedException;
import com.dxy.hms.model.entity.User;
import com.dxy.hms.service.UserService;
import com.dxy.hms.utils.JwtUtil;
import com.dxy.hms.utils.LoginUtil;
import com.dxy.hms.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
@Api(tags = "授权接口")
@RestController
@RequestMapping("/hms/auth")
public class AuthController {


    @Autowired
    private UserService userService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public Resp<String> login(@RequestBody User user, HttpServletResponse response) {
        User dbUser = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getAccount, user.getAccount()));
        if (dbUser == null) {
            throw new UnifiedException(StatusMessageEnum.ACCOUNT_NOT_EXIST);
        }

        if (!Objects.equals(MD5Util.getEncryptPassword(user.getPassword()), dbUser.getPassword())) {
            throw new UnifiedException(StatusMessageEnum.PWD_ERROR);
        }

        if (!dbUser.getStatus().equals(AppConstant.USER_ENABLE_STATUS)) {
            throw new UnifiedException(StatusMessageEnum.ACCOUNT_DISABLE);
        }

        String token = JwtUtil.createToken(String.valueOf(dbUser.getId()));
        LoginUtil.setOnline(token);

        if (JwtUtil.useCookie) {
            // 将数据保存到cookie中
            Cookie cookie = new Cookie(LoginUtil.TOKEN_KEY, token);
            cookie.setMaxAge((int) (JwtUtil.expire * 60)); // 秒
            cookie.setPath("/");
            cookie.setDomain(JwtUtil.site);
            cookie.setHttpOnly(true);// 前端JS无法获取到了
            response.addCookie(cookie);
            return Resp.bizSuccess();
        } else {
            // 不使用cookie则把token给前端放在请求头中
            return Resp.bizSuccess(token);
        }
    }

    @ApiOperation("退出")
    @PostMapping("/logout")
    public Resp logout(HttpServletRequest request, HttpServletResponse response) {

        String token = LoginUtil.getToken(request);

        // 1. 移除本地缓存的登录状态
        LoginUtil.setOffline(token);

        // 2. 删除cookie（cookie本身没有删除操作，可以通过新建cookie覆盖）
        if (JwtUtil.useCookie) {
            Cookie cookie = new Cookie(LoginUtil.TOKEN_KEY, "");//不要设置为null，防止有些浏览器不支持
            cookie.setMaxAge(0);// >0表示设置存货时间，=0表示立即删除，-1表示等回话结束后删除
            cookie.setPath("/");
            cookie.setDomain(JwtUtil.site);
            response.addCookie(cookie);
        }

        return Resp.bizSuccess();
    }
}
